package tasksimulator;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;

/**
 *
 * @author Jonas
 */
public class TaskRunner extends Thread {

    int taskMeanTime;
    int amountOfTasks;
    long timeSpentOnDB = 0;

    public TaskRunner(int taskMeanTime, int amountOfTasks) {
        this.taskMeanTime = taskMeanTime;
        this.amountOfTasks = amountOfTasks;
    }

    @Override
    public void run() {
        Random r = new Random(TaskSimulator.seed);
        for (int i = 0; i < this.amountOfTasks; i++) {
            //calcula um tempo aleatório para a tarefa de acordo com a média especificada
            int taskTime = taskMeanTime;//(int) Math.abs(taskMeanTime + (taskMeanTime * r.nextGaussian()));
            //pega uma nova tarefa
            Task task = Task.nextTask();
            //seta a data de início da tarefa
            task.start();
            try {
                long time0 = System.currentTimeMillis();
                //armazena a tarefa inicialmente no banco
                Databaser.storeTask(task);
                //espera o tempo de execução da tarefa
                long time1 = System.currentTimeMillis();
                this.timeSpentOnDB += (time1 - time0);
                this.sleep(taskTime * 1000);
                task.end();
                //faz o update dos dados da execução
                time0 = System.currentTimeMillis();
                Databaser.updateTask(task);
                time1 = System.currentTimeMillis();
                this.timeSpentOnDB += (time1 - time0);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
        
        try{
           
           OutputStream out = new FileOutputStream("output.data");
           String temp = this.timeSpentOnDB+"\n";
           out.write(temp.getBytes());
        
        } catch(Exception e){
        	e.printStackTrace();
        }
        
        
        System.out.println(this.timeSpentOnDB);
    }
}
